<?php

// +----------------------------------------------------------------------
// |物流服务层
// +----------------------------------------------------------------------

namespace app\admin\system;

use app\common\Model\ConfigModel;
use think\facade\Cache;
use think\facade\Db;
use  app\common\Model\StroageModel;
use app\admin\Model\CountryModel;


/**
 * 物流渠道管理
 */
class LogisticsService
{


      /**
    * 快递列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  getList($params){
        $where = [];       
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        }   
        if($params['name']){
            $where[] = ['name', 'like', '%'. $params['name']. '%'];
        }    
         
        $field =  'id,name,code,status,createtime,p_id,sender';          
        $authgroups_list = Db::name('logistice_channel')->field($field)->where($where)->order('id asc,status asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();     
        if($authgroups_list['data']){
            foreach ($authgroups_list['data'] as $key => $value) {
               //  $Supplier_list['data'][$key]['sp_author'] =json_decode($value['sp_author'],true);
                $sender=json_decode($value['sender'],true);
               if($sender){           
                   $authgroups_list['data'][$key]['username']=$sender['username'];
                   $authgroups_list['data'][$key]['tel']=$sender['tel'];
                   $authgroups_list['data'][$key]['address']=$sender['address'];
                   $authgroups_list['data'][$key]['zipcode']=$sender['zipcode'];
               }
            }
       }
        $data['list']=$authgroups_list['data'];
        $data['total']=$authgroups_list['total'];  
        return $data; 
    }

       /**
    * 快递列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function create($params){
   
        $sender=['username'=>isset($params['username'])?$params['username']:'','tel'=>isset($params['tel'])?$params['tel']:'','address'=>isset($params['address'])?$params['address']:'','zipcode'=>isset($params['zipcode'])?$params['zipcode']:''];
        $data=[
            'p_id' => $params['p_id'],
            'status' => $params['status'],  
            'name' => $params['name'],    
            'code' => $params['code'],  
            'sender' => json_encode($sender,JSON_UNESCAPED_UNICODE),           
        ];
        if($params['id']){          
             //有值则说明是修改     
             $result =  Db::name('logistice_channel')->where('id',$params['id'])->update($data);
        }else{
            $data['createtime']=datetime();
            $data['createymd']=(int)date('Ymd',time());
             //执行添加数据
             $result =  Db::name('logistice_channel')->save($data);
        }
        if($result){
            return true;
        }else{
            error('修改失败');
        }      
    }


    /**
    * 快递服务商列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function getproviderList($params){
    
        $where = [];       
        if($params['status']==2){
            $where[] = ['status', '=', 0];
        }else  if($params['status']==1){
            $where[] = ['status', '=', 1];
        }   
        if($params['name_Cn']){
            $where[] = ['name_Cn', 'like', '%'. $params['name_Cn']. '%'];
        }     
         
        $field =  'id,name_Cn,name_En,status,createtime';          
        $authgroups_list = Db::name('logistice_provider')->field($field)->where($where)->order('id asc,status asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();     
        $data['list']=$authgroups_list['data'];
        $data['total']=$authgroups_list['total'];  
        return $data;

    }



       /**
    * 快递服务商添加与修改
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function provider_create($params){    
        $data=[
            'name_Cn' => $params['name_Cn'],
            'status' => $params['status'],  
            'name_En' => $params['name_En'],    
            'account_name' => $params['account_name'],  
            'account_password' => $params['account_password'],   
            'authorizeCode' => $params['authorizeCode'],   
        ];

        if($params['id']){          
             //有值则说明是修改     
             $result =  Db::name('logistice_provider')->where('id',$params['id'])->update($data);
        }else{
            $data['createtime']=datetime();
            $data['createymd']=(int)date('Ymd',time());
             //执行添加数据
             $result =  Db::name('logistice_provider')->save($data);
        }
        if($result){
            return true;
        }else{
            error('修改失败');
        }      
    }

     /**
    * 快递资费列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function  charge($params){
         
        $where[] =['is_used','=',1];       
        if($params['name_En']){
            $where[] = ['name_En', '=', $params['name_En']];
        } 
        if($params['p_id']){
            $where[] = ['p_id', '=', $params['p_id']];
        } 
        if($params['countrys']){
            $where[] = ['countrys', '=', $params['countrys']];
        }     
        
         
        $field =  'id,name_En,countrys,dealcost,unitcost,minweight,maxweight,peak_period_cost,p_id,createtime';          
        $list = Db::name('logistice_charge')->field($field)->where($where)->order('id asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();  
        if($list['data']){
              //获取国家
               $config_list=(new CountryModel())->getcountryAllList();   
               $logistice_channel =  Db::name('logistice_channel')->column('name,code','code');            
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['range'] = $value['minweight'].'-'.$value['maxweight'] ;
                $list['data'][$key]['countrysCN'] = $config_list[$value['countrys']]['name'];
                $list['data'][$key]['name_Cn'] = $logistice_channel[$value['name_En']]['name'];
            }
        }
        $data['list']=$list['data'];
        $data['total']=$list['total'];          
        return $data;
    }

      /**
    * 快递资费添加与修改
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function   charge_create($params){
        $data=[
            'name_En' => $params['name_En'],
            'countrys' => $params['countrys'],  
            'unitcost' => $params['unitcost'],    
            'dealcost' => $params['dealcost'],  
            'minweight' => $params['minweight'],   
            'maxweight' => $params['maxweight'],
            'p_id'      => $params['p_id'],      
        ];

        if($params['id']){          
             //有值则说明是修改     
             $result =  Db::name('logistice_charge')->where('id',$params['id'])->update($data);
        }else{
            $data['createtime']=datetime();
            $data['createymd']=(int)date('Ymd',time());
             //执行添加数据
             $result =  Db::name('logistice_charge')->save($data);
        }
        if($result){
            return true;
        }else{
            error('修改失败');
        }      
    }

      /**
    * 通过物流商id查询物流渠道
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function channel_list($params){
        if(isset($params['countrys'])){
            $countrys=$params['countrys'];
        }
        if(isset($params['name_En'])){
            $name_En=$params['name_En'];
        }
        if(isset($params['p_id'])){
            $p_id=$params['p_id'];
        }    
        $type=$params['type'];// 1:查询快递渠道  2:快递资费
        if($type==1){
            $result =  Db::name('logistice_channel')->where('p_id', $p_id)->where('status', 1)->column('name,code');
            if(empty($result)){
                error('该物流商没有启用或没有渠道');
            }
        }else if($type==2){
            $result =  Db::name('logistice_charge')->where('name_En', $name_En)->where('is_used', 1)->where('countrys', $countrys)->select()->toArray();        
            if($result){
                foreach ($result as $key => $value) {
                    $result[$key]['range'] = $value['minweight'].'-'.$value['maxweight'] ;
                }
            }   
        }
     
        return $result;        
    }

   /**
    * 快递资费删除
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function charge_detele($params){     
      $result =  Db::name('logistice_charge')->where('id',$params['id'])->update(['is_used'=>0]);    
        if($result){
            return true;
        }else{
            error('修改失败');
        }         
    }
    
     /**
    * 快递规则列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function rule($params,$logistice_providerist_isu){
        $where[] =['storage_id','=',$params['storage_id']];       
        $field =  'id,name,rules,is_used,name_Cn,name_En,storage_id,sort,p_id,createtime';          
        $list = Db::name('logistice_rule')->field($field)->where($where)->order('id asc')->paginate(['list_rows'=>$params['pagesize'],'page'=>$params['pagenum']])->toArray();  
        if($list['data']){           
            foreach ($list['data'] as $key => $value) {
                $logistice_providerist_isu=array_column($logistice_providerist_isu,null,'id');
                $rule= json_decode($value['rules'],true);
                $list['data'][$key]['platforms'] = $rule['platform'];
                $list['data'][$key]['providerist_name'] = $logistice_providerist_isu[$value['p_id']]['name_Cn'];
                $list['data'][$key]['platform'] =explode(',', $rule['platform']);
                $list['data'][$key]['maxweight'] = $rule['maxweight'];
                $list['data'][$key]['country'] = $rule['country'];
            }
        }
        $data['list']=$list['data'];
        $data['total']=$list['total'];          
        return $data;
    }

     /**
    * 快递规则列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function   rule_create($params){
         $result =  Db::name('logistice_channel')->where('code', $params['code'])->where('status', 1)->column('name,code','code');
         //仓库的信息
        $Model=new StroageModel();
        $storagelist =  $Model->getActivelist();  
        $storagelist =array_column($storagelist,null,'id');
        
        $rules=[
             'platform'=>implode(',', $params['platform']),
             'maxweight'=>$params['maxweight'],
             'country'=>$params['country'],
        ];
        $data=[
            'p_id' => $params['p_id'],
            'name' => $storagelist[$params['storage_id']]['name'].'-'. $result[$params['code']]['name'],  
            'name_En' =>$params['code'],    
            'name_Cn' =>$result[$params['code']]['name'],  
            'storage_id' => $params['storage_id'],   
            'sort' => $params['sort'],  
            'rules'=>json_encode($rules,JSON_UNESCAPED_UNICODE),           
       ];
         if($params['id']){          
             //有值则说明是修改     
             $result =  Db::name('logistice_rule')->where('id',$params['id'])->update($data);
        }else{
            $data['createtime']=datetime();
            $data['createymd']=(int)date('Ymd',time());
             //执行添加数据
             $result =  Db::name('logistice_rule')->save($data);
        }
        if($result){
            return true;
        }else{
            error('修改失败');
        }      
    }
    /**
    * 快递规则列表
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function rule_delete($params){
        $id=$params['id'];
        $result = Db::name('logistice_rule')->where('id','=',$id)->delete();
        if($result){
            return true;
        }else{
            error('删除失败');
        }    
    }


   /**
    * 运费模板
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function logistice_template(){
        $data=Db::name('logistice_template')->alias('a')->join('shops b','a.shop_id=b.id')->field('a.*,b.name as shop_name')->order('a.id asc')->select()->toArray();
        return $data; 
    }

     /**
    * 通过店铺id查询运费模板
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function logistice_template_list($params){
       $where=$where_shop=[];
      
       if(isset($params['shop_id'])){       
          $shop_id=$params['shop_id'];
           $where[] = ['shop_id', '=',  $shop_id];    
           $where_shop[] = ['id', '=',  $shop_id];    
       }  
       //查询店铺默认模板信息     
        $shippingmodelid=Db::name('shops')->where($where_shop)->field('shippingmodelid ')->find();       
        $data=Db::name('logistice_template')->where($where)->field('shippingmodelid as id,modelname as name')->select()->toArray();
        $datas['list']=$data;
        $datas['shippingmodelid']=$shippingmodelid['shippingmodelid'];
        return $datas; 
    }

      /**
    * 运费测算
    * @param array $param 前台传过来的参数  
    * @return array
    */
    public static function freighttrial($params){
        $param=$params['params'];
        $weight=$param['weight'];
        $country=$param['countrys'];
        $type=$param['type'];//类型，fee 是运费测算，price 是产品单价测算
        if($type=='fee'){
            // $where['_string']   = 'FIND_IN_SET(\'' . addslashes($code) . '\', countrys)';

            $where = [
                'countrys'  => $country,
                'is_used'   => 1,               
            ];   

            $list  = Db::name('logistice_charge')->where($where)->where('minweight', '<=', $weight)->where('maxweight', '>', $weight)->select()->toArray();           
            if(empty($list)){
                error('该区域没有设置运费，请设置区域费用');
            }
            $logistice_channel = Db::name('logistice_channel')->column('code,name','code');
            foreach ($list as $k => $v) { 
                    $list[$k]['logistics_name']           = $logistice_channel[$v['name_En']]['name'];
                    $list[$k]['fee']            = round(($v['dealcost'] + $v['unitcost'] * $weight), 2);                  
                    $list[$k]['weight_input']   = $weight;             
            }
            return $list;
        }


    }
}

